package com.shop.resource.service.search.impl;

import com.shop.resource.bean.input.QryArticlesIPo;
import com.shop.resource.service.search.IArticleSearchService;
import com.teemor.common.bean.util.BeanConvertor;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.ClearScrollResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @author zhoulk
 * @date: 2019/11/27
 */
@Service
public class ArticleSearchServiceImpl implements IArticleSearchService {

    @Autowired
    private RestHighLevelClient highLevelClient;


    @Override
    public void testRequest() throws IOException {
//        IndexRequest request = new IndexRequest("jsons", "supermap", "1")
////                .source(singletonMap("feature", "high-level-rest-client"))
////                .setRefreshPolicy(IMMEDIATE);
//        GetRequest getRequest = new GetRequest("article", "_doc", "1");
//        GetResponse response = highLevelClient.get(getRequest);
//        System.out.println(response.toString());

        QueryBuilder matchQuery = new MatchQueryBuilder("user_name", "zhou");

        String[] fields = {"title", "content"};
        QueryBuilder multiMatchQuery = new MultiMatchQueryBuilder("匹配的词条", fields);
        final Scroll scroll = new Scroll(TimeValue.timeValueMinutes(10L));
        SearchRequest searchRequest = new SearchRequest("article");
        searchRequest.scroll(scroll);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder bqb = new BoolQueryBuilder();
        bqb.must(QueryBuilders.matchQuery("atc_id", 1));
        bqb.must(QueryBuilders.matchQuery("user_name", "zhou"));

        QueryBuilder matchQuery2 = new MatchQueryBuilder("atc_id", "1");

        searchSourceBuilder.query(multiMatchQuery).postFilter(bqb);
        searchSourceBuilder.size(5);
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT); //通过发送初始搜索请求来初始化搜索上下文
        String scrollId = searchResponse.getScrollId();
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        SearchHit searchHit = searchHits[0];
        String source = searchHit.getSourceAsString();

        while (searchHits != null && searchHits.length > 0) { //通过循环调用搜索滚动api来检索所有搜索命中，直到没有文档返回
            //处理返回的搜索结果
            SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId); //创建一个新的搜索滚动请求，保存最后返回的滚动标识符和滚动间隔
            scrollRequest.scroll(scroll);
            searchResponse = highLevelClient.scroll(scrollRequest, RequestOptions.DEFAULT);
            scrollId = searchResponse.getScrollId();
            searchHits = searchResponse.getHits().getHits();
        }
        ClearScrollRequest clearScrollRequest = new ClearScrollRequest(); //完成滚动后，清除滚动上下文
        clearScrollRequest.addScrollId(scrollId);
        ClearScrollResponse clearScrollResponse = highLevelClient.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
        boolean succeeded = clearScrollResponse.isSucceeded();
    }

    @Override
    public String searchArticles(String paaram) {
        QryArticlesIPo qryArticlesIPo = BeanConvertor.convertBean(paaram, QryArticlesIPo.class);


        String[] fields = new String[5];
        QueryBuilder multiMatchQuery = new MultiMatchQueryBuilder("匹配的词条", fields);
        final Scroll scroll = new Scroll(TimeValue.timeValueMinutes(10L));
        SearchRequest searchRequest = new SearchRequest("article");
        searchRequest.scroll(scroll);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        QueryBuilder matchQuery = new MatchQueryBuilder("user_name", "zhou");
        searchSourceBuilder.query(multiMatchQuery).postFilter(matchQuery);
        searchSourceBuilder.size(5);
        searchRequest.source(searchSourceBuilder);
        String scrollId = null;
        try {
            SearchResponse searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT); //通过发送初始搜索请求来初始化搜索上下文
            scrollId = searchResponse.getScrollId();
            SearchHit[] searchHits = searchResponse.getHits().getHits();

            while (searchHits != null && searchHits.length > 0) { //通过循环调用搜索滚动api来检索所有搜索命中，直到没有文档返回
                //处理返回的搜索结果
                SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId); //创建一个新的搜索滚动请求，保存最后返回的滚动标识符和滚动间隔
                scrollRequest.scroll(scroll);
                searchResponse = highLevelClient.scroll(scrollRequest, RequestOptions.DEFAULT);
                scrollId = searchResponse.getScrollId();
                searchHits = searchResponse.getHits().getHits();
            }

        } catch (Exception ignored) {

        } finally {


            if (StringUtils.isNotBlank(scrollId)) {
                boolean succeeded = false;
                do {
                    ClearScrollRequest clearScrollRequest = new ClearScrollRequest(); //完成滚动后，清除滚动上下文
                    clearScrollRequest.addScrollId(scrollId);
                    ClearScrollResponse clearScrollResponse = null;
                    try {
                        clearScrollResponse = highLevelClient.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
                        succeeded = clearScrollResponse.isSucceeded();
                    } catch (IOException e) {

                    }
                } while (!succeeded);
            }
        }
        return null;
    }
}

